export function getQueryVariable(variable) {
  const query = window.location.href.split("?")?.[1];
  console.log('getQueryVariable', query)
  if (!query) return;
  const vars = query.split('&');
  for (var i = 0; i < vars.length; i++) {
    const pair = vars[i].split('=');
      if (decodeURIComponent(pair[0]) == variable) {
          return decodeURIComponent(pair[1]);
      }
  }
}

export function urlAppendQeury(url, query) {
  if (query) {
    let queryString = Object.keys(query)
      .map(function(key) {
        return encodeURIComponent(key) + '=' + encodeURIComponent(query[key]);
      })
      .join('&');
    if (url.indexOf('?') === -1) {
      queryString = '?' + queryString;
    } else {
      queryString = '&' + queryString;
    }
    return url + queryString;
  }
  return url;
}

// 函数防抖
export const debounce = (func, time = 300) => {
  let timer = null
  return function (...params) {
      clearTimeout(timer)
      timer = setTimeout(() => {
          func.apply(this, params)
      }, time)
  }
}
export const isUrl = str => pattern.url.test(str);

export const pattern = {
  url: new RegExp(
    '^(?!mailto:)(?:(?:http|https|ftp)://|//)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-*)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-*)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$',
    'i',
  ),
  idCard: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
};

export const certTypes = [
  {
    label: '身份证',
    key: 'idCard',
    value: '111',
  }
]
/**
 * @description: 获取今天到前几天 ['3-5','3-6']
 * @param {Number} 天数
 * @return: 今天到前几天
 */
export function lastDays(range) {
  const date = new Date(), res = []
  let day = date.getDate(),
    month = date.getMonth(),
    year = date.getFullYear()
  for(let i = 1; i <= range; i++) {
    res.unshift(formatTime(day, month))
    if(day === 1) {
      let curDay = new Date(year,month,day)
      let lastDay = new Date(curDay-1000*60*60*24)
      month = lastDay.getMonth()
      day = lastDay.getDate()
    } else {
      day = day - 1
    }
  }
  return res
}

// 日期格式化
export function formatTime(day, month, year) {
  if (month < 9) {
    month = '0' + (month+1)
  } else {
    month = month + 1
  }

  if (day < 10) {
    day = '0' + day
  }
  return month + '-' + day
}

//获取当前时间
export function getNowFormatDate() {
  let date = new Date();
  let seperator1 = "-";
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let strDate = date.getDate();
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = "0" + strDate;
  }
  let currentdate = year + seperator1 + month + seperator1 + strDate;
  return currentdate;
}

// 首字母大写
export function capitalize(str) {
  return str.charAt(0).toUpperCase() + str.slice(1)
}

//判断是否为空格
export function isSpace (str) {
  if(str.match(/^[ ]+$/)){
    return true;
  }
  return false;
}

export function getDays(start, end) {
  let ret = [];
  let range = (end - start) / 1000 / 60 / 60 / 24 + 1;
  let day = end.getDate();
  let month = end.getMonth();
  let year = end.getFullYear();
  for (let i = 1; i <= range; i++) {
    ret.unshift(formatTime(day, month));
    if (day === 1) {
      let curDay = new Date(year, month, day);
      let lastDay = new Date(curDay - 1000 * 60 * 60 * 24);
      month = lastDay.getMonth();
      day = lastDay.getDate();
    } else {
      day = day - 1;
    }
  }

  return ret;
}

/**
 * @description: 是否存在重复的元素
 * @param {Array} arry 数组
 * @return: false 未重复 、true 重复
 */
 export function isDulication (arry) {
  if (!Array.isArray(arry)) return false;
  for (let i = 0; i < arry.length; i++) {
    let cur = arry[i];
    let idx = arry.indexOf(cur);
    if (idx !== -1 && idx !== i) {
      return true
    }
  }
  return false;
}

export const passwordRegExp = /^[\da-zA-Z!@#$%^&*_=(),.<>*]+$/;

/**
 * @description: 是否要跳转上一页
 * @param {String} dataLength 数据的长度
 * @param {String} selectdLength 选中的数据长度
 * @param {Object} page
  * @param {Number} page.size 分页大小
  * @param {Number} page.current 当前页
  * @param {Number} page.total  总条数
 * @return {Boolean}
 */
export function canGotoPrePage(dataLength, selectdLength, page) {
  // 只要一个为null或者undefined 放回false
  if (!dataLength|| !selectdLength || !page.size || !page.current || !page.total)
    return false
  if (dataLength === selectdLength
    && page.current != 1
    && page.size * page.current >= page.total) {
      return true
  } else {
    return false
  }
}

export function getUuid() {
  const S4 = () => (((1+Math.random())*0x10000)|0).toString(16).substring(1);
  return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}

// 检测当前宿主环境是否是浏览器
export const inBrowser = typeof window !== 'undefined'

// 获取当浏览器的user Agent
export const UA = inBrowser && window.navigator.userAgent.toLowerCase()

// IE浏览器判断
export const isIE = UA && /msie|trident/.test(UA)

export const idCardRegExp = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;

export const isIE11 = navigator.userAgent.toLowerCase().match(/rv:([\d.]+)\) like gecko/) ? true : false


export function checkIllegalChars(rule, value, callback) {
  const regex = /[<>]/
  if (regex.test(value)) {
    let msg=''
    if (value.indexOf('<')!=-1) {
      msg += '<';
    }
    if (value.indexOf('>')!=-1) {
      msg += '>';
    }
    callback(new Error('存在非法字符：'+msg))
  } else {
    callback()
  }
}

export function NocheckIllegalChars(rule, value, callback) {
  const regex = /[\[]]/
  if (regex.test(value)) {
    callback(new Error('存在非法字符'))
  } else {
    callback()
  }
}

export function checkSimpleIllegalChars(rule, value, callback) {
  const regex = /[\[`~$^*()=|';'\\<>~￥……*|【】‘\]]/
  if (regex.test(value)) {
    callback(new Error('存在非法字符'))
  } else {
    callback()
  }
}

/**
 * @description: 给table的表头字段添加必选样式
 * @param {array} requredProps 需要添加的表头下标，从左边第一个字段0开始
 * @param {string} selector 选择器 表格的class
 * @param {string} requiredClassName 必选的样式
 * @return:
 */
export function tableHeaderPropAddRequired(requredProps, selector, requiredClassName = 'prop-required') {
  const thes = document.querySelector(selector).querySelectorAll('.el-table__header-wrapper th')
  Array.from(thes).forEach((th, i) => {
    if (requredProps.includes(i)) {
      th.querySelector('div').className += ` ${requiredClassName}`
    }
  })
}

export function focusAlertBtn() {
  setTimeout(() => {
    const btns = [...document.querySelectorAll('.el-message-box__btns button')]
    if (!btns || btns.length === 0) return;
    btns.forEach(btn => {
      btn.blur()
    })
  }, 0)
}

export function hasChinese(str) {
  return /.*[\u4e00-\u9fa5]+.*/.test(str)
}

/**
 * @description: 双向映射
 * @param {type}
 * @return:
 */
export function ENUM (obj) {
  let ret = JSON.parse(JSON.stringify(obj))
  Object.keys(obj).forEach(key => {
    let value = obj[key];
    ret[ret[key] = value] = key;
  })
  return ret
}

export const getValueByPath = function(object, prop) {
  prop = prop || '';
  const paths = prop.split('.');
  let current = object;
  let result = null;
  for (let i = 0, j = paths.length; i < j; i++) {
    const path = paths[i];
    if (!current) break;

    if (i === j - 1) {
      result = current[path];
      break;
    }
    current = current[path];
  }
  return result;
};

export const setValueByPath = function (object, prop, value) {
  if (isUnDef(prop)) return;
  const paths = prop.split('.');
  let current = object;
  for (let i = 0, len = paths.length; i < len; i++) {
    if (!current) break;
    let path = paths[i];
    if (i === len - 1) {
      current[path] = value;
      break;
    }
    current = current[path];
  }
}

// 由于菜单路由里有按钮授权(根据路由路径上的参数显示隐藏按钮)，需要在路由路径上添加菜单id正常访问(显示按钮)
export function findRouteUrlByPath(state, path) {
  let result;
  const walk = (nodes) => {
    for (let node of nodes) {
      if (node.path === path) {
        result = node;
        return;
      }
      node.children && walk(node.children)
    }
  }
  walk(state.routes)
  if (!result) {
    return;
  }
  let query = result.meta && result.meta.id ? `/${result.meta.id}` : "";
  return result.path + query;
}

export const hasAsterisk = str => {
  if (!str) return false;
  return /\*/.test(str);
};

export const clone = val => JSON.parse(JSON.stringify(val));

export const isUnDef = val => val === undefined || val === null;

// 脱敏
export function desensitization(str, beginLen, endlen, minLen = 0) {
  str = str + ''
  let len = str.length
  if (!str || minLen > len) return str
  let beginStr = str.slice(0, beginLen)
  let endStr = str.slice(len-endlen)
  let middleStr = str.slice(beginLen, len-endlen).replace(/[\s\S]/ig, '*')
  return beginStr + middleStr + endStr
}

/**
 * @description: 获取第一个condition为true的节点
 * @param {Array} data 树数组，每个元素都是树结构的对象
 * @param {Function} condition 条件
 * @return: 节点以及其父节点
 */
 export function getCheckFirstNodeByCondition(data, condition) {
  if (!data || data.length === 0) return null;
  const traverse = (data) => {
    let t
    for(let i = 0; i < data.length; i++) {
      t = data[i]
      if (condition(t) === true) return [t]
      if (t.children && t.children.length !== 0) {
        const result = traverse(t.children)
        if (result) {
          return [t, ...result]
        }
      }
    }
  };
  const path = traverse(data);
  if (path==undefined || path.length === 0) {
     return null;
  } else {
    return {
      node: path[path.length-1],
      parents: path.slice(0, path.length-1)
    };
  };
}

let a = null
// 模拟点击
export function simulateClick( url, { isBlank = false, isLoading = false } = {}) {
  a = a || document.createElement('a');
  isBlank ? a.target = '_blank' : "";
  a.href = url;
  isLoading && Loading.service({
    lock: true,
    text: '正在处理...',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.5)'
  })
  if (isIE && isIE11) {
    // fix ie10及以下模拟点击失效
    document.body.appendChild(a).click()
  } else {
    a.click()
  }
}

export function arrayMakeMap(target, key) {
  const result = []
  target.map(v => v[key]).map((v, i) => {
    result[v] = target[i]
  })
  return result
}

// 判断变量是不是字符类型
export function isString(a) {
  return Object.prototype.toString.call(a) === "[object String]"
}
